from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker, Session
from sqlalchemy.pool import StaticPool
import redis
from app.config import settings

# 创建数据库引擎
engine = create_engine(
    settings.DATABASE_URL,
    poolclass=StaticPool,
    connect_args={"check_same_thread": False} if "sqlite" in settings.DATABASE_URL else {}
)

# 创建会话工厂
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)

# 声明基类
Base = declarative_base()

# Redis 客户端
redis_client = redis.from_url(settings.REDIS_URL, decode_responses=True)


def get_db() -> Session:
    """获取数据库会话"""
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()


def get_redis():
    """获取 Redis 客户端"""
    return redis_client


def init_db():
    """初始化数据库表"""
    # 导入所有模型以确保它们被注册
    from app.models import user, script, job, datasource, api_service, data_map
    
    # 创建所有表
    Base.metadata.create_all(bind=engine) 